import Vue from 'vue'
import VueRouter from 'vue-router'
import store from "../store/index"

Vue.use(VueRouter)

function fn(msg,next){
  let routeEnter = store.state.user.menus_url
  if(routeEnter.includes(msg)){
    next()
  }else{
    next("/")
  }
}

export const secondRouter = [{
  path: "menu",
  meta: {
    title: "菜单管理"
  },
  beforeEnter(to, from, next){
    fn("/menu",next)
  },
  component: () => import("../page/menu/menu.vue")
}, {
  path: "role",
  meta: {
    title: "角色管理"
  },
  beforeEnter(to, from, next){
    fn("/role",next)
  },
  component: () => import("../page/role/role.vue")
}, {
  path: "manage",
  meta: {
    title: "管理员管理"
  },
  beforeEnter(to, from, next){
    fn("/manage",next)
  },
  component: () => import("../page/manage/manage.vue")
}, {
  path: "cate",
  meta: {
    title: "商品分类"
  },
  beforeEnter(to, from, next){
    fn("/cate",next)
  },
  component: () => import("../page/cate/cate.vue")
}, {
  path: "specs",
  meta: {
    title: "商品规格"
  },
  beforeEnter(to, from, next){
    fn("/specs",next)
  },
  component: () => import("../page/specs/specs.vue")
}, {
  path: "goods",
  meta: {
    title: "商品管理"
  },
  beforeEnter(to, from, next){
    fn("/goods",next)
  },
  component: () => import("../page/goods/goods.vue")
}, {
  path: "member",
  meta: {
    title: "会员管理"
  },
  beforeEnter(to, from, next){
    fn("/member",next)
  },
  component: () => import("../page/member/member.vue")
}, {
  path: "banner",
  meta: {
    title: "轮播图管理"
  },
  beforeEnter(to, from, next){
    fn("/banner",next)
  },
  component: () => import("../page/banner/banner.vue")
}, {
  path: "seckill",
  meta: {
    title: "秒杀活动"
  },
  beforeEnter(to, from, next){
    fn("/seckill",next)
  },
  component: () => import("../page/seckill/seckill.vue")
}]

const routes = [
  {
    path: "/login",
    component: () => import("../page/login/login.vue")
  }, {
    path: "/",
    component: () => import("../page/index/index.vue"),
    children: [{
      path: "",
      component: () => import("../page/home/home.vue")
    },
    ...secondRouter
    ]
  }]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  // 如果去的是登录页就不拦截
  if(to.path=="/login"){
    next()
    return
  }
  // 判断用户是否登陆过，如果没登录过就不让去，登陆过了才让去
  if(store.state.user.token){
    next()
    return
  }
  next("/login")
})

export default router
